<?php

namespace App\Http\Controllers\Network;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\NetworkCreditRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\NetworkGoodsOrderModel;
use App\Models\yb\NetworkReturnBucketModel;
use App\Models\yb\OrderRefundModel;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoadingOrderController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  订单列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderListing(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $type = $request->post('type');

        if($type != ''){
            $network_order = NetworkGoodsOrderModel::where(['network_id'=>$user_data['id']])->where(['status'=>$type])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
        }else{
            $network_order = NetworkGoodsOrderModel::where(['network_id'=>$user_data['id']])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
        }

        foreach($network_order as $key=>$val){
            $goods_count = 0;
            if(!empty($val['goods_list'])){
                $network_goods = $val['goods_list'];
                foreach($network_goods as $k=>$v){
                    $goods_data = GoodsModel::where(['id'=>$v['goods_id']])->first();
                    $network_goods[$k]['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
                    $goods_count = $goods_count+$v['number'];
                }
                $network_order[$key]['goods_list'] = $network_goods;
                $network_order[$key]['goods_count'] = $goods_count;
            }
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$network_order]);

    }

    /**
     * Get a JWT via given credentials.
     *  订单删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderDelete(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $order_sn= $request->post('order_sn');

        if (empty($order_sn)) {
            return response()->json(['code' => '201', 'msg' => '订单不存在']);
        }

        $network_order = NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($network_order) || $network_order['status'] != 2){
            return response()->json(['code' => '201', 'msg' => '该订单不可删除']);
        }

        DB::beginTransaction();

        if(!empty($network_order['transaction_id'])){

            $payment = Factory::payment(NetworkGoodsOrderModel::getRefundConfig());

            $refund_order_sn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            $result = $payment->refund->byTransactionId($network_order['transaction_id'], "Yz".time(), $network_order['amount'], $network_order['amount'], [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => '退款',
                'body'=>$order_sn
            ]);

            if($result['return_code'] == 'SUCCESS'){
                OrderRefundModel::insert([
                    'order_sn' => $order_sn,
                    'refund_order_sn' => $refund_order_sn,
                    'admin_id' => $network_order['network_id'],
                    'admin_openid' => $openid,
                    'amount' => $network_order['amount'],
                    'created_at' => date('Y-m-d H:i:s',time()),
                ]);
            }
        }

        NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->update([
            'status' => '5'
        ]);

        $network_credit_record = NetworkCreditRecordModel::where(['relation_data'=>$order_sn])->get();
        if(!empty($network_credit_record)){
            foreach($network_credit_record as $key=>$val){

                if($val['type'] == 1){
                    NetworkGoodsModel::where(['network_id'=>$val['network_id'],'goods_id'=>$val['goods_id']])->increment('return_credit',$val['number']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $val['number'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加信用',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 7,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }
                if($val['type'] == 3){
                    AdminUserModel::where(['id'=>$network_order['network_id']])->increment('distribution_price',$val['amount']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加配送费',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 8,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }
                if($val['type'] == 5){
                    NetworkGoodsModel::where(['network_id'=>$val['network_id'],'goods_id'=>$val['goods_id']])->decrement('barrel_deposit',$val['amount']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $val['number'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加桶押金',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 9,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }

            }
        }

        DB::commit();

        return response()->json(['code'=>'200','msg' => '请求成功']);
    }

    /**
     * Get a JWT via given credentials.
     *  订单取消
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderCancel(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $order_sn= $request->post('order_sn');

        if (empty($order_sn)) {
            return response()->json(['code' => '201', 'msg' => '订单不存在']);
        }

        $network_order = NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($network_order) || $network_order['status'] != 0){
            return response()->json(['code' => '201', 'msg' => '该订单不可取消']);
        }

        DB::beginTransaction();

        if(!empty($network_order['transaction_id'])){

            $payment = Factory::payment(NetworkGoodsOrderModel::getRefundConfig());

            $refund_order_sn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            $result = $payment->refund->byTransactionId($network_order['transaction_id'], "Yz".time(), $network_order['amount'], $network_order['amount'], [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => '退款',
                'body'=>$order_sn
            ]);

            if($result['return_code'] == 'SUCCESS'){
                OrderRefundModel::insert([
                    'order_sn' => $order_sn,
                    'refund_order_sn' => $refund_order_sn,
                    'admin_id' => $network_order['network_id'],
                    'admin_openid' => $openid,
                    'amount' => $network_order['amount'],
                    'created_at' => date('Y-m-d H:i:s',time()),
                ]);
            }
        }

        NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->update([
            'status' => '5'
        ]);

        $network_credit_record = NetworkCreditRecordModel::where(['relation_data'=>$order_sn])->get();
        if(!empty($network_credit_record)){
            foreach($network_credit_record as $key=>$val){

                if($val['type'] == 1){
                    NetworkGoodsModel::where(['network_id'=>$val['network_id'],'goods_id'=>$val['goods_id']])->increment('return_credit',$val['number']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $val['number'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加信用',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 7,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }
                if($val['type'] == 3){
                    AdminUserModel::where(['id'=>$network_order['network_id']])->increment('distribution_price',$val['amount']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加配送费',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 8,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }
                if($val['type'] == 5){
                    NetworkGoodsModel::where(['network_id'=>$val['network_id'],'goods_id'=>$val['goods_id']])->decrement('barrel_deposit',$val['amount']);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $val['network_id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $val['number'],
                        'amount' => $val['amount'],
                        'remark' => '取消订单增加桶押金',
                        'status' => 1,
                        'relation_data' => $order_sn,
                        'type' => 9,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ]);
                }

            }
        }

        DB::commit();

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }

    /**
     * Get a JWT via given credentials.
     *  网点还桶
     * @return \Illuminate\Http\JsonResponse
     */
    public function ReturnBucket(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $goods_id = $request->post('goods_id');

        if (empty($goods_id)) {
            return response()->json(['code' => '201', 'msg' => '请选择商品']);
        }

        $goods_data = GoodsModel::where(['id'=>$goods_id])->first();

        $order_sn = $request->post('order_sn');

        if (empty($order_sn)) {
            return response()->json(['code' => '201', 'msg' => '请选择订单']);
        }

        $network_goods = NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$goods_id])->first();

        if(empty($network_goods)){
            return response()->json(['code' => '201', 'msg' => '您还没有此商品']);
        }

        $bucket_number= $request->post('bucket_number');

        if (empty($bucket_number)) {
            return response()->json(['code' => '201', 'msg' => '桶数量']);
        }

        NetworkReturnBucketModel::insert([
            'network_id' => $user_data['id'],
            'order_sn' => $order_sn,
            'goods_id' => $goods_id,
            'bucket_number' => $bucket_number,
            'barrel_deposit' => $goods_data['barrel_deposit'],
            'total_barrel_deposit' => $goods_data['barrel_deposit']*$bucket_number,
            'status' => 0,
            'created_at' => date('Y-m-d H:i:s',time())
        ]);

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }


}
